//
//  ViewController.swift
//  FallowProject
//
//  Created by 李晋 on 2017/7/25.
//  Copyright © 2017年 李晋. All rights reserved.
//  语音识别 SpeechKit.framework

import UIKit
import Speech

class ViewController: UIViewController {
    fileprivate let speechRecognizer = SFSpeechRecognizer(locale: Locale.init(identifier: "zh_Hans_CN"))

    fileprivate var recognitionRequest: SFSpeechAudioBufferRecognitionRequest?  //识别请求
    fileprivate var recognitionTask: SFSpeechRecognitionTask?       // 提供识别请求的结果
    fileprivate let audioEngine = AVAudioEngine()       //
    
    @IBOutlet weak var textView: UITextView!
    @IBOutlet weak var microphoneButton: UIButton!
    
    @IBAction func microphoneTapped(_ sender: UIButton) {
        if audioEngine.isRunning {
            audioEngine.stop()
            recognitionRequest?.endAudio()
            microphoneButton.isEnabled = false
            microphoneButton.setTitle("Start Recording", for: .normal)
        } else {
            startRecording()
            microphoneButton.setTitle("Stop Recording", for: .normal)
        }
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        microphoneButton.isEnabled = false
        speechRecognizer?.delegate = self
        
        // 2
        SFSpeechRecognizer.requestAuthorization{
            (authStatus) in
            var isButtionEnabled = false
            
            switch authStatus {
            case .authorized:
                isButtionEnabled = true
            case .denied:
                isButtionEnabled = false
                print("用户拒绝接受语音识别")
            case .notDetermined:
                isButtionEnabled = false
                print("语音识别功能没有经过认可")
            case .restricted:
                isButtionEnabled = false
                print("当前设备不能语音识别")
                
            }
            self.microphoneButton.isEnabled = isButtionEnabled
        }
        startRecording()
    }
    
}

extension ViewController {
    fileprivate func startRecording() {
        // 1
        if recognitionTask != nil {
            recognitionTask?.cancel()
            recognitionTask = nil
        }
        // 2
        let audioSession = AVAudioSession.sharedInstance()
        do {
            try audioSession.setCategory(AVAudioSessionCategoryRecord)
            try audioSession.setMode(AVAudioSessionModeMeasurement)
            try audioSession.setActive(true, with: .notifyOthersOnDeactivation)
        } catch {
            print("audioSession的属性设置失败")
        }
        // 3
        recognitionRequest = SFSpeechAudioBufferRecognitionRequest()
        // 4
        guard let inputNode = audioEngine.inputNode else {
            fatalError("Audio engine has no input node")
        }
        // 5
        guard let recognitionRequest = recognitionRequest else {
            fatalError("Unable to create an SFSpeechAudioBufferRecognitionRequest object")
        }
        // 6
        recognitionRequest.shouldReportPartialResults = true
        // 7
        recognitionTask = speechRecognizer?.recognitionTask(with: recognitionRequest, resultHandler: {
            (result, error) in
            var isFinal = false
            if result != nil {
                self.textView.text = result?.bestTranscription.formattedString
                isFinal = (result?.isFinal)!
            }
            
            if error != nil || isFinal {
                self.audioEngine.stop()
                inputNode.removeTap(onBus: 0)
                
                self.recognitionRequest = nil
                self.recognitionTask = nil
                
                self.microphoneButton.isEnabled = true
            }
        })
        
        let recordingFormat = inputNode.outputFormat(forBus: 0)
        inputNode.installTap(onBus: 0, bufferSize: 1024, format: recordingFormat) { (buffer, when) in
            self.recognitionRequest?.append(buffer)
        }
        
        audioEngine.prepare()
        
        do {
            try audioEngine.start()
        } catch {
            print("audioEngine couldn't start beacause of an error.")
        }
        
        textView.text = "Say something, I'm listening!"
    }
}

extension ViewController: SFSpeechRecognizerDelegate {
    func speechRecognizer(_ speechRecognizer: SFSpeechRecognizer, availabilityDidChange available: Bool) {
        if available {
            microphoneButton.isEnabled = true
        } else {
            microphoneButton.isEnabled = false
        }
    }
}
